//
//  AppDelegate.m
//  DemoProject
//
//  Created by hao on 2018/7/10.
//  Copyright © 2018年 hao. All rights reserved.
//

#import "AppDelegate.h"
#import "UserNotifiViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "RootTabBarControllerConfig.h"
#import "RootPublishButton.h"

@interface AppDelegate () <UNUserNotificationCenterDelegate>

#pragma mark - 后台运行任务所需参数
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskInvalid;
@property (nonatomic, assign) NSTimeInterval tenMinute;///申请后台运行的时间,单位:秒
@property (nonatomic, assign) NSTimeInterval timerSecond;///定时器走过的时间,单位:秒
@property (nonatomic, strong) NSTimer *backgroundTimer;
@property (nonatomic, strong) NSMutableArray *taskIdArray;
#pragma mark -

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    /** launchOptions: 表示APP不同的启动方式
        1. launchOptions = nil, 用户自己点击启动APP
        2. launchOptions[UIApplicationLaunchOptionsURLKey] != nil urlscheme方式启动
        3. launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] != nil 远程方式启动
        4. launchOptions[UIApplicationLaunchOptionsLocalNotificationKey] != nil  本地通知方式启动, iOS 10以后 "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]"
     */
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    // 注册tabbar上的发布按钮(不规则，微博、闲鱼的样式)
    [RootPublishButton registerPlusButton];
    self.window.rootViewController = [[RootTabBarControllerConfig alloc] init].tabBarController;
    [self.window makeKeyAndVisible];
    [self setupUserNotificationCenter];
    return YES;
}

#pragma mark - UNUserNotificationCenter
- (void)setupUserNotificationCenter
{
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *notifiCenter = [UNUserNotificationCenter currentNotificationCenter];
        notifiCenter.delegate = self;
        // 注册获取授权
        [notifiCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert + UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"UNUserNotificationCenter授权成功");
            } else if (error) {
                NSLog(@"UNUserNotificationCenter授权失败: error -> %@", error);
            }
        }];
        // 获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
        [notifiCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"UNNotificationSettings -> %@", settings);
        }];
    }
}

#pragma mark - UNUserNotificationCenterDelegate
// iOS10新增：处理前台收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
API_AVAILABLE(ios(10.0)){
    NSLog(@"%s", __func__);
    //1. 处理通知
    
    //2. 处理完成后条用 completionHandler ，用于指示在前台显示通知的形式
    completionHandler(UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
API_AVAILABLE(ios(10.0)){
    NSLog(@"%s", __func__);
    // 获取通知的内容
    UNNotificationContent *content = response.notification.request.content;
    NSLog(@"通知内容: content -> %@", content);
    completionHandler();
}

#pragma mark - 后台运行任务
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    //    [self beginBackground];
}

- (void)beginBackground
{
    if (self.tenMinute >= 600) {///申请后台运行超过600秒,就不需要申请了
        return ;
    }
    self.backgroundTaskInvalid = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        /*
         beginBackgroundTaskWithExpirationHandler 方法以及 - (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(nullable NSString *)taskName expirationHandler:(void(^ __nullable)(void))handler 与 endBackgroundTask方法必须一一对应,有一个begin就有一次end
         */
        NSLog(@"申请时间完毕,再次申请 或者 够10分钟不会再次申请");
        ///去做事情
        [self beginBackground];
    }];
    [self.taskIdArray addObject:@(self.backgroundTaskInvalid)];
    self.tenMinute = self.tenMinute + [[UIApplication sharedApplication] backgroundTimeRemaining];
    NSLog(@"剩余时间:%f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
    [self.backgroundTimer invalidate];
    self.backgroundTimer = nil;
    self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doTaskinBack) userInfo:nil repeats:YES];
}
- (void)doTaskinBack
{
    NSLog(@"监控时间:%@",[NSDate date]);
    self.timerSecond++;
    if (self.timerSecond >= 600) {///当运行超过600秒,直接且统一干掉
        [self.taskIdArray enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"taskId====%lu",(unsigned long)obj.unsignedIntegerValue);
            [[UIApplication sharedApplication] endBackgroundTask:obj.unsignedIntegerValue];
        }];
        self.backgroundTaskInvalid = UIBackgroundTaskInvalid;
    }
}
- (NSMutableArray *)taskIdArray
{
    if (!_taskIdArray) {
        _taskIdArray = [NSMutableArray array];
    }
    return _taskIdArray;
}
#pragma mark -

@end
